/**
 * Preload script for Electron
 * 设置安全策略和API暴露
 */

const { contextBridge, ipcRenderer } = require('electron')

// 暴露安全的API给渲染进程
contextBridge.exposeInMainWorld('electronAPI', {
  // 菜单事件监听
  on: (channel, callback) => {
    const validChannels = [
      'menu-save-file',
      'menu-undo',
      'menu-edit-params',
      'menu-reset-params',
      'menu-window-cascade',
      'menu-window-tile',
      'menu-open-settings'
    ]
    
    if (validChannels.includes(channel)) {
      ipcRenderer.on(channel, callback)
    }
  },
  
  // 移除事件监听
  off: (channel, callback) => {
    const validChannels = [
      'menu-save-file',
      'menu-undo',
      'menu-edit-params',
      'menu-reset-params',
      'menu-window-cascade',
      'menu-window-tile',
      'menu-open-settings'
    ]
    
    if (validChannels.includes(channel)) {
      ipcRenderer.off(channel, callback)
    }
  },
  
  // 文件操作API
  selectFile: (options) => ipcRenderer.invoke('dialog:selectFile', options),
  selectDirectory: (options) => ipcRenderer.invoke('dialog:selectDirectory', options),
  
  // 系统信息
  getSystemInfo: () => ipcRenderer.invoke('system:getInfo'),
  
  // 配置管理
  saveConfig: (config) => ipcRenderer.invoke('config:save', config),
  loadConfig: () => ipcRenderer.invoke('config:load'),
  
  // 日志记录
  log: (level, message) => ipcRenderer.invoke('log:write', { level, message, timestamp: new Date().toISOString() }),
  
  // 项目操作
  createProjectStructure: (projectData) => ipcRenderer.invoke('project:createStructure', projectData),
  validateProject: (projectPath) => ipcRenderer.invoke('project:validate', projectPath),
  scanProject: (projectPath) => ipcRenderer.invoke('project:scan', projectPath),
  
  // 文件操作
  readFile: (filePath) => ipcRenderer.invoke('file:read', filePath),
  writeFile: (filePath, content) => ipcRenderer.invoke('file:write', filePath, content),
  fileExists: (filePath) => ipcRenderer.invoke('file:exists', filePath),
  listFiles: (dirPath) => ipcRenderer.invoke('file:list', dirPath),
  deleteFile: (targetPath) => ipcRenderer.invoke('file:delete', targetPath),
  renameFile: (oldPath, newPath) => ipcRenderer.invoke('file:rename', oldPath, newPath),
  revealInExplorer: (targetPath) => ipcRenderer.invoke('reveal-in-explorer', targetPath),
  
  // SIMION自动化操作
  runSimionAutomation: (config) => ipcRenderer.invoke('simion:run', config),
  stopSimionAutomation: () => ipcRenderer.invoke('simion:stop'),
  getSimionStatus: () => ipcRenderer.invoke('simion:status'),
  getSimionLogs: () => ipcRenderer.invoke('simion:logs'),
  stopPythonServer: () => ipcRenderer.invoke('stopPythonServer'),
  
  // Python服务器管理
  checkPythonServerStatus: () => ipcRenderer.invoke('checkPythonServerStatus'),
  restartPythonServer: () => ipcRenderer.invoke('restartPythonServer')
})

// 防止页面被嵌入到其他网站
if (window.top !== window.self) {
  window.top.location = window.self.location
}
